package com.lsc.record.core.service.impl;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.lsc.record.core.entity.DmContent;
import com.lsc.record.core.entity.DmType;
import com.lsc.record.core.mapper.DmContentMapper;
import com.lsc.record.core.mapper.DmTypeMapper;
import com.lsc.record.core.service.ContentServcie;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;

@Service
public class ContentServiceImpl implements ContentServcie {

	@Resource
	private DmContentMapper contentDao;
	
	@Resource
	private DmTypeMapper typeMapper;

	@Override
	public DmContent create(DmContent content, String userName) throws Exception {
		if(StringUtils.isEmpty(content.getDocId())) {
			throw new Exception("CONTENT中没有文档ID");
		}
		
		Row docObj = Db.selectOneBySql("SELECT * FROM DM_DOCUMENT_VIEW WHERE ID=?",content.getDocId());
		if(docObj==null || docObj.isEmpty()) {
			throw new Exception("文档数据为找到");
		}
		String typeName = docObj.getString("TYPE_NAME");
		if(StringUtils.isEmpty(typeName)) {
			throw new Exception("文档的文档类型数据为空");
		}
		
		Map<String,Object> where =new HashMap<>();
		where.put("NAME", typeName);
		DmType typeObj = typeMapper.selectOneWithRelationsByMap(where);
		
		String storeBasePath = typeObj.getStore().getStoreValue();
		
		if(content.getInputStream()!=null) {			
			
			Row datatick = Db.selectOneBySql("SELECT SN_CONTENT_DATATIKET.NEXTVAL as datatickt FROM dual; ");
			String fullSavePath =getSavePath(storeBasePath, datatick.getInt("DATATICKT"), content.getFormatName());
			content.setFilePath(fullSavePath);
			saveInputStreamToFile(content.getInputStream(), fullSavePath);
			contentDao.insert(content, true);
			return content;
		}
		return null;
	}

	@Override
	public DmContent getCurrentContent(String docId) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public DmContent updateVersion(DmContent content, String docId, boolean isPrimayVersion, String userName)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Boolean deleteAllContent(String docId, String userName) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Boolean deleteVersion(String docId, Integer primaryVersion, Integer subVersion, String userName)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	private String getSavePath(String storeBase,int dataTickt,String formatName) {
		StringBuffer sb = new StringBuffer(storeBase);
		if(!storeBase.endsWith("/") && !storeBase.endsWith("\\")) {
			sb.append("/");
		}
		String dataTicktValue = convertToFixedLengthHex(dataTickt);
		String savePath = addSlashes(dataTicktValue)+"."+formatName;
		sb.append(savePath);
		return sb.toString();
	}
	
	private void saveInputStreamToFile(InputStream inputStream, String filePath) throws Exception {
	    // Step 1: Create a File object representing the target file with its multi-level path
	    File targetFile = new File(filePath);

	    // Step 2: Ensure the parent directory of the target file exists; create it if not
	    Path parentDir = targetFile.toPath().getParent();
	    if (!parentDir.toFile().exists()) {
	        Files.createDirectories(parentDir);
	    }

	    // Step 3: Copy data from InputStream to the target file
	    try (InputStream in = inputStream) {
	        Files.copy(in, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
	    }
	}
	
	
	
	private String convertToFixedLengthHex(int decimalNumber) {
	    // Step 1: Convert the decimal number to a hexadecimal string
	    String hexString = Integer.toHexString(decimalNumber);

	    // Step 2: Ensure the resulting string has a length of exactly 12 by adding leading zeros if necessary
	    while (hexString.length() < 12) {
	        hexString = "0" + hexString;
	    }

	    return hexString;
	}

	private String addSlashes(String input) {
	    // Step 1: Determine the current operating system and corresponding path separator
	    char pathSeparator='/';
//	    if (File.separatorChar == '\\') { // Windows
//	        pathSeparator = '\\';
//	    } else { // Assume Linux or macOS (other Unix-like systems)
//	        pathSeparator = '/';
//	    }

	    // Step 2: Add slashes after every two characters in the input string
	    StringBuilder result = new StringBuilder(input.length() + 5); // Reserve space for potential extra slashes
	    for (int i = 0; i < input.length(); i++) {
	        result.append(input.charAt(i));
	        if ((i + 1) % 2 == 0 && i < input.length() - 1) { // Only append slash if not at the end of the string
	            result.append(pathSeparator);
	        }
	    }

	    return result.toString();
	}
}
